/* weatherscrape.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Console program that prints the 10-day forecast from www.weather.com.
*/

const char *DEFAULT_ZIP = "02140";

#include "_web/Curl.h"

#include <string>
#include <iostream>
#include <fstream>
#include <cctype>
#include <ctime>
#include <sstream>
#include <vector>

using std::string;
using std::cout;
using std::cerr;
using std::endl;
using std::ofstream;
using std::ostream;
using std::ios;
using std::time;
using std::time_t;
using std::tm;
using std::localtime;
using std::mktime;
using std::ostringstream;
using std::vector;



void ParseDaily(const string &page, ostream &out);
void ParseHourly(const string &page, ostream &out);
string PrintDate(const tm &date);
string Extract(const string &page, size_t &pos, const string &prefix, const string &suffix);



int main(int argc, char *argv[])
{
	string zipCode = DEFAULT_ZIP;
	string outFilePath;
	char type = 'd';
	for(int i = 1; i < argc; ++i)
	{
		if(argv[i][0] == '-')
		{
			if(argv[i][1] == 'h')
				type = 'h';
			else if(argv[i][1] == 'd')
				type = 'd';
		}
		else
		{
			// Assume the input is a zip code.
			// It must be exactly five digits.
			int digits = 0;
			for( ; isdigit(argv[i][digits]); ++digits) {}
			
			if(digits == 5 && !argv[i][digits])
				zipCode = argv[i];
			else
				outFilePath = argv[i];
		}
	}
	
	Curl curl;
	curl.Init();
	if(!curl)
	{
		cerr << "Unable to initialize the web connection." << endl;
		return 1;
	}
	
	string path = ((type == 'h') ?
		"http://www.weather.com/weather/hourbyhour/" : 
		"http://www.weather.com/weather/tenday/") + zipCode;
	const string &page = curl.Get(path);
	
	if(page.empty())
	{
		cerr << "No response when trying to download the weather page." << endl;
		return 1;
	}
	
	ostream *out = &cout;
	ofstream fout;
	if(!outFilePath.empty())
	{
		fout.open(outFilePath.c_str(), ios::app | ios::ate | ios::out);
		out = &fout;
	}
	if(type == 'd')
		ParseDaily(page, *out);
	else
		ParseHourly(page, *out);

	return 0;	
}



void ParseDaily(const string &page, ostream &out)
{
	vector<string> phrases;
	for(size_t pos = 0; pos < page.size(); )
	{
		pos = page.find("fc-wx-phrase", pos);
		if(pos == string::npos)
			break;
		
		phrases.push_back(Extract(page, pos, ">", "<"));
	}
	
	vector<string> temps;
	for(size_t pos = 0; pos < page.size(); )
	{
		pos = page.find("twc-forecast-temperature\"", pos);
		if(pos == string::npos)
			break;
		
		temps.push_back(Extract(page, pos, ">", "&deg;"));
		// Trim white space.
		size_t i = 0;
		while(i < temps.back().size() && temps.back()[i] <= ' ')
			++i;
		temps.back() = temps.back().substr(i);
	}
	
	vector<string> precip;
	for(size_t pos = 0; pos < page.size(); )
	{
		pos = page.find("twc-line-precip", pos);
		if(pos == string::npos)
			break;
		
		precip.push_back(Extract(page, pos, "<strong>", "%"));
	}
	
	time_t today = time(NULL);
	tm date = *localtime(&today);
	for(unsigned i = 0; i < phrases.size() && i < temps.size() / 2 && i < precip.size(); ++i)
	{
		string timestamp = PrintDate(date);
		// Add 1 to the day and make sure the date is still valid.
		++date.tm_mday;
		mktime(&date);
		
		out << timestamp << '\t' << phrases[i] << '\t'
			<< temps[i] << '\t' << temps[i + temps.size() / 2] << '\t'
			<< precip[i] << endl;
	}
}



void ParseHourly(const string &page, ostream &out)
{
	time_t today = time(NULL);
	tm date = *localtime(&today);
	
	size_t pos = 0;
	while(true)
	{
		static const string BEGIN = "<div class=\"hbhTDTime\"><div>";
		pos = page.find(BEGIN, pos);
		if(pos == string::npos)
			return;
		pos += BEGIN.length();
		
		string hour = page.substr(pos, page.find("</div>", pos) - pos);
		// Move padding spaces to the start of the string.
		while(hour.length() < 5)
			hour = " " + hour;
		hour[3] += 'A' - 'a';
		hour[4] += 'A' - 'a';
		
		static const string CONDITION = "<div class=\"hbhTDCondition\"><div><b>";
		pos = page.find(CONDITION, pos);
		pos += CONDITION.length();
		string temp = page.substr(pos, page.find("</b>", pos) - pos);
		// Extract the numbers before the degrees HTML entity.
		unsigned degPos = 1;
		while(degPos < temp.size() && temp[degPos] >= '0' && temp[degPos] <= '9')
			++degPos;
		temp = temp.substr(0, degPos);
		while(temp.size() < 2)
			temp = " " + temp;
		
		static const string BR = "<br>";
		pos = page.find(BR, pos);
		pos += BR.length();
		string forecast = page.substr(pos, page.find("</div>", pos) - pos);
		
		static const string PRECIP = "<div class=\"hbhTDPrecip\"><div>";
		pos = page.find(PRECIP, pos);
		pos += PRECIP.length();
		string precip = page.substr(pos, page.find("</div>", pos) - pos);
		// Extract the numbers before the percent sign.
		precip = precip.substr(0, precip.find('%') + 1);
		while(precip.size() < 3)
			precip = " " + precip;
		
		out << hour << '\t' << forecast << '\t' << temp << '\t' << precip << endl;
	}
}



string PrintDate(const tm &date)
{
	ostringstream out;
	out<<(1900 + date.tm_year);
	out.width(2);
	out.fill('0');
	out<<(1 + date.tm_mon);
	out.width(2);
	out.fill('0');
	out<<(date.tm_mday);
	
	return out.str();
}



string Extract(const string &page, size_t &pos, const string &prefix, const string &suffix)
{
	size_t start = page.find(prefix, pos) + prefix.length();
	size_t end = page.find(suffix, start);
	
	pos = end + suffix.length();
	
	return string(page, start, end - start);
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */
